﻿#include "oglmanager.h"
#include <QKeyEvent>
#include <QDebug>
#include "resourcemanager.h"
#include "cube.h"

const QVector3D CAMERA_POSITION(0.0f, 0.0f, 3.0f);
const QVector3D LIGHT_POSITION(1.0f, 0.8f, 0.8f);

Cube *cube;

OGLManager::OGLManager(GLuint w, GLuint h)
{
    this->width = w;
    this->height = h;
    for (GLuint i = 0; i != 1024; ++i)
        keys[i] = GL_FALSE;

}

OGLManager::~OGLManager()
{
    delete this->camera;
    ResourceManager::clear();
}

void OGLManager::init()
{
    cube = new Cube();

    this->camera = new Camera(CAMERA_POSITION);
    cube->init();
    core = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_3_Core>();

    ResourceManager::loadShader("cube", ":/shaders/res/shaders/cube.vert", ":/shaders/res/shaders/cube.frag");
    ResourceManager::loadShader("light", ":/shaders/res/shaders/light.vert", ":/shaders/res/shaders/light.frag");


    ResourceManager::getShader("cube").use().setVector3f("objectColor", QVector3D(1.0f, 0.5f, 0.31f));
    ResourceManager::getShader("cube").use().setVector3f("lightColor", QVector3D(1.0f, 1.0f, 1.0f));
    ResourceManager::getShader("cube").use().setVector3f("lightPos", LIGHT_POSITION);

    ResourceManager::getShader("light").use().setVector3f("lightColor", QVector3D(1.0f, 1.0f, 1.0f));

    //开启状态
    core->glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    core->glEnable(GL_DEPTH_TEST);
}

void OGLManager::processInput(GLfloat dt)
{
    if (keys[Qt::Key_W])
        camera->processKeyboard(FORWARD, dt);
    if (keys[Qt::Key_S])
        camera->processKeyboard(BACKWARD, dt);
    if (keys[Qt::Key_A])
        camera->processKeyboard(LEFT, dt);
    if (keys[Qt::Key_D])
        camera->processKeyboard(RIGHT, dt);
    if (keys[Qt::Key_E])
        camera->processKeyboard(UP, dt);
    if (keys[Qt::Key_Q])
        camera->processKeyboard(DOWN, dt);
}


void OGLManager::update(GLfloat dt)
{
    QMatrix4x4 projection, model;
    projection.perspective(camera->zoom, (GLfloat)width / (GLfloat)height, 0.1f, 200.f);

    ResourceManager::getShader("cube").use().setMatrix4f("projection", projection);
    ResourceManager::getShader("cube").use().setMatrix4f("view", camera->getViewMatrix());
    ResourceManager::getShader("cube").use().setMatrix4f("model", model);
    ResourceManager::getShader("cube").use().setVector3f("viewPos", camera->position);

    model.translate(LIGHT_POSITION);
    model.scale(0.2f);
    ResourceManager::getShader("light").use().setMatrix4f("projection", projection);
    ResourceManager::getShader("light").use().setMatrix4f("view", camera->getViewMatrix());
    ResourceManager::getShader("light").use().setMatrix4f("model", model);
}

void OGLManager::resize(GLuint w, GLuint h)
{
    core->glViewport(0, 0, w, h);
}

void OGLManager::draw(GLfloat dt)
{
    core->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    ResourceManager::getShader("cube").use();
    cube->drawCube();

    ResourceManager::getShader("light").use();
    cube->drawLight();
}
